import axios from 'axios'
import adapter from 'axios-miniprogram-adapter'
import store from '@/store/index.js'
// #ifdef MP-WEIXIN 
axios.defaults.adapter = adapter
// #endif
const baseURL = "https://api-hmugo-web.itheima.net/api/public/v1/"
const instance = axios.create({
  baseURL: baseURL
})
instance.interceptors.request.use((config) => {
  // 接口不需要token加了不报错
  // if (store.state.user.token) {
  //   config.headers.Authorization = store.state.user.token
  // }
  // 接口不需要token加了报错
  if (config.url.startsWith('/my') && store.state.user.token) {
    config.headers.Authorization = store.state.user.token
  }

  return config
}, (err) => {
  return Promise.reject(err)
})
instance.interceptors.response.use((res) => {
  if (res.data.meta.status === 200) {
    return res.data
  } else {
    // 失败
    // 错误提示
    uni.$showToast(res.data.meta.msg)
    // 抛出一个promise错误信息:中止后面.then执行。执行.catch
    return Promise.reject(new Error(res.data.meta.msg))
  }
}, (err) => {
  return Promise.reject(err)
}) // wx===>uni
uni.http = instance
uni.baseURL = baseURL
export default instance